package com.blacktech.dbu.core.exception;

import com.blacktech.dbu.core.response.ApiResponse;
import com.blacktech.dbu.core.response.ResponseCode;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.util.stream.Collectors;

/**
 * 全局异常处理器
 *
 * @author Yanyunsong
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<ApiResponse<Object>> handleBusinessException(
            BusinessException ex, HttpServletRequest request) {

        log.warn("业务异常: [{}] {} - {}", ex.getCode(), ex.getMessage(), request.getRequestURI());

        ApiResponse<Object> response = ApiResponse.error(ex.getCode(), ex.getMessage(), ex.getData());

        // 根据错误码确定HTTP状态码
        HttpStatus httpStatus = determineHttpStatusByErrorCode(ex.getCode());

        return ResponseEntity.status(httpStatus).body(response);
    }

    /**
     * 处理参数验证异常（@RequestBody @Valid）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ApiResponse<Object>> handleMethodArgumentNotValidException(
            MethodArgumentNotValidException ex, HttpServletRequest request) {

        String errorMessage = ex.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));

        log.warn("参数验证异常: {} - {}", errorMessage, request.getRequestURI());

        ApiResponse<Object> response = ApiResponse.badRequest(errorMessage);

        return ResponseEntity.badRequest().body(response);
    }

    /**
     * 处理参数绑定异常（@ModelAttribute @Valid）
     */
    @ExceptionHandler(BindException.class)
    public ResponseEntity<ApiResponse<Object>> handleBindException(
            BindException ex, HttpServletRequest request) {

        String errorMessage = ex.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));

        log.warn("参数绑定异常: {} - {}", errorMessage, request.getRequestURI());

        ApiResponse<Object> response = ApiResponse.badRequest(errorMessage);

        return ResponseEntity.badRequest().body(response);
    }

    /**
     * 处理约束违反异常（@Validated）
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<ApiResponse<Object>> handleConstraintViolationException(
            ConstraintViolationException ex, HttpServletRequest request) {

        String errorMessage = ex.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(", "));

        log.warn("约束违反异常: {} - {}", errorMessage, request.getRequestURI());

        ApiResponse<Object> response = ApiResponse.badRequest(errorMessage);

        return ResponseEntity.badRequest().body(response);
    }

    /**
     * 处理方法参数类型不匹配异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResponseEntity<ApiResponse<Object>> handleMethodArgumentTypeMismatchException(
            MethodArgumentTypeMismatchException ex, HttpServletRequest request) {

        String errorMessage = String.format("参数 '%s' 类型错误，期望类型: %s",
                ex.getName(),
                ex.getRequiredType() != null ? ex.getRequiredType().getSimpleName() : "unknown");

        log.warn("参数类型错误: {} - {}", errorMessage, request.getRequestURI());

        ApiResponse<Object> response = ApiResponse.badRequest(errorMessage);

        return ResponseEntity.badRequest().body(response);
    }

    /**
     * 处理认证异常
     */
    @ExceptionHandler(AuthenticationException.class)
    public ResponseEntity<ApiResponse<Object>> handleAuthenticationException(
            AuthenticationException ex, HttpServletRequest request) {

        log.warn("认证异常: {} - {}", ex.getMessage(), request.getRequestURI());

        ApiResponse<Object> response = ApiResponse.unauthorized("认证失败: " + ex.getMessage());

        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
    }

    /**
     * 处理授权异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public ResponseEntity<ApiResponse<Object>> handleAccessDeniedException(
            AccessDeniedException ex, HttpServletRequest request) {

        log.warn("授权异常: {} - {}", ex.getMessage(), request.getRequestURI());

        ApiResponse<Object> response = ApiResponse.forbidden("权限不足: " + ex.getMessage());

        return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
    }

    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ApiResponse<Object>> handleIllegalArgumentException(
            IllegalArgumentException ex, HttpServletRequest request) {

        log.warn("非法参数异常: {} - {}", ex.getMessage(), request.getRequestURI());

        ApiResponse<Object> response = ApiResponse.badRequest(ex.getMessage());

        return ResponseEntity.badRequest().body(response);
    }

    /**
     * 处理非法状态异常
     */
    @ExceptionHandler(IllegalStateException.class)
    public ResponseEntity<ApiResponse<Object>> handleIllegalStateException(
            IllegalStateException ex, HttpServletRequest request) {

        log.error("非法状态异常: {} - {}", ex.getMessage(), request.getRequestURI(), ex);

        ApiResponse<Object> response = ApiResponse.error(ResponseCode.CONFLICT.getCode(), ex.getMessage());

        return ResponseEntity.status(HttpStatus.CONFLICT).body(response);
    }

    /**
     * 处理通用运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<ApiResponse<Object>> handleRuntimeException(
            RuntimeException ex, HttpServletRequest request) {

        log.error("运行时异常: {} - {}", ex.getMessage(), request.getRequestURI(), ex);

        // 检查是否是自定义的业务异常（直接抛出的RuntimeException）
        if (isCustomBusinessException(ex)) {
            ApiResponse<Object> response = ApiResponse.businessError(ex.getMessage());
            return ResponseEntity.badRequest().body(response);
        }

        ApiResponse<Object> response = ApiResponse.error(ResponseCode.INTERNAL_SERVER_ERROR.getCode(),
                                                        "服务器内部错误，请稍后重试");

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
    }

    /**
     * 处理通用异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponse<Object>> handleException(
            Exception ex, HttpServletRequest request) {

        log.error("系统异常: {} - {}", ex.getMessage(), request.getRequestURI(), ex);

        ApiResponse<Object> response = ApiResponse.error(ResponseCode.INTERNAL_SERVER_ERROR.getCode(),
                                                        "系统异常，请联系管理员");

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
    }

    /**
     * 根据错误码确定HTTP状态码
     */
    private HttpStatus determineHttpStatusByErrorCode(Integer errorCode) {
        if (errorCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }

        // 业务错误码映射
        if (errorCode >= 1000 && errorCode < 2000) {
            return HttpStatus.BAD_REQUEST;
        }

        // 标准HTTP状态码
        ResponseCode responseCode = ResponseCode.getByCode(errorCode);
        return switch (responseCode) {
            case SUCCESS, CREATED, ACCEPTED -> HttpStatus.OK;
            case NO_CONTENT -> HttpStatus.NO_CONTENT;
            case BAD_REQUEST, VALIDATION_FAILED -> HttpStatus.BAD_REQUEST;
            case UNAUTHORIZED -> HttpStatus.UNAUTHORIZED;
            case FORBIDDEN -> HttpStatus.FORBIDDEN;
            case NOT_FOUND -> HttpStatus.NOT_FOUND;
            case METHOD_NOT_ALLOWED -> HttpStatus.METHOD_NOT_ALLOWED;
            case CONFLICT -> HttpStatus.CONFLICT;
            case TOO_MANY_REQUESTS -> HttpStatus.TOO_MANY_REQUESTS;
            case INTERNAL_SERVER_ERROR, SERVICE_UNAVAILABLE, GATEWAY_TIMEOUT ->
                HttpStatus.INTERNAL_SERVER_ERROR;
            default -> HttpStatus.INTERNAL_SERVER_ERROR;
        };
    }

    /**
     * 判断是否为自定义的业务异常（通过异常消息特征判断）
     */
    private boolean isCustomBusinessException(RuntimeException ex) {
        String message = ex.getMessage();
        if (message == null) {
            return false;
        }

        // 检查常见的业务异常消息特征
        return message.contains("不存在") ||
               message.contains("已存在") ||
               message.contains("不能为空") ||
               message.contains("格式错误") ||
               message.contains("长度超出") ||
               message.contains("权限不足") ||
               message.contains("未授权") ||
               message.contains("已禁用") ||
               message.contains("已锁定");
    }
}